const socket = new WebSocket("ws://192.168.123.160:8080/ws");

// Preload notification sound
const notificationSound = new Audio("sound/newMessage.mp3");

// 添加一个全局变量来存储所有聊天记录
const messageStore = {};

// 添加全局变量存储最后更新时间
const lastUpdateTimes = JSON.parse(localStorage.getItem('lastUpdateTimes') || '{}');

// 添加保存时间戳的函数
function saveLastUpdateTimes() {
    localStorage.setItem('lastUpdateTimes', JSON.stringify(lastUpdateTimes));
}

socket.onmessage = function(event) {
    const msg = JSON.parse(event.data);
    const currentUser = localStorage.getItem('currentUser');
    const friend = msg.from_user === currentUser ? msg.to_user : msg.from_user;
    
    if (!messageStore[friend]) {
        messageStore[friend] = [];
    }
    messageStore[friend].push(msg);
    
    // 如果当前正在查看该好友的聊天，则立即显示新消息
    const currentChat = document.getElementById("chat-name").textContent;
    if (currentChat === friend) {
        showChatMessages(friend);
    }
    
    // 更新左侧好友列表
    updateMessages();
    
    // 播放提示音
    notificationSound.play();
};

document.getElementById("send-btn").addEventListener("click", sendMessage);
document.getElementById("message-text").addEventListener("keydown", function(event) {
    if (event.key === "Enter" && !event.shiftKey) { // allow shift+enter for newline
        event.preventDefault(); // prevent newline on Enter
        sendMessage();
    }
});

function sendMessage() {
    let messageTextEl = document.getElementById("message-text");
    let messageText = messageTextEl.value;
    if (messageText.trim() === "") {
        return;
    }
    
    // 获取聊天对象名称
    let chatPartner = document.getElementById("chat-name").textContent.trim();
    if (!chatPartner || chatPartner === "聊天界面") {
        alert("请选择聊天好友后再发送消息！");
        return;
    }
    
    // 从 localStorage 获取当前用户名
    const currentUser = localStorage.getItem('currentUser');
    if (!currentUser) {
        alert("会话已过期，请重新登录");
        window.location.href = "/login";
        return;
    }
    // 构造消息对象
    let msgObj = {
        from: currentUser,
        to: chatPartner,
        message: messageText
    };

    // 将消息显示在聊天窗口
    let messageDiv = document.createElement("div");
    messageDiv.classList.add("message", "sent");
    messageDiv.textContent = messageText;
    document.getElementById("messages").appendChild(messageDiv);

    // 通过WebSocket发送消息
    socket.send(JSON.stringify(msgObj));

    // 构造消息对象后，添加到本地存储
    const timestamp = new Date().toISOString();
    const newMsg = {
        from_user: currentUser,
        to_user: chatPartner,
        message: messageText,
        timestamp: timestamp,
        is_read: true
    };
    
    if (!messageStore[chatPartner]) {
        messageStore[chatPartner] = [];
    }
    messageStore[chatPartner].push(newMsg);

    // 更新并保存最后更新时间
    // lastUpdateTimes[chatPartner] = new Date(timestamp).getTime();
    // saveLastUpdateTimes();

    // 清空输入框并恢复默认高度
    messageTextEl.value = "";
    messageTextEl.style.height = "auto";
    scrollMessagesToBottom();
}

// Helper function to auto-scroll the messages container to the bottom
function scrollMessagesToBottom() {
    let messagesEl = document.getElementById("messages");
    messagesEl.scrollTop = messagesEl.scrollHeight;
}

document.addEventListener("DOMContentLoaded", function() {
    const addFriendBtn = document.getElementById("add-friend-btn");
    console.log("addFriendBtn:", addFriendBtn);

    // Add friend on Enter key press
    const friendNameInput = document.getElementById("friendname");
    friendNameInput.addEventListener("keypress", function(e) {
        if (e.key === "Enter") {
            e.preventDefault();
            const friendName = this.value.trim();
            if (!friendName) {
                alert("请输入好友用户名");
                return;
            }
            
            fetch("/addFriend", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ friend: friendName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    addFriendToList(friendName);
                    this.value = ""; // Clear input after successful add
                } else {
                    showFriendError(`用户 ${friendName} 不存在`);
                }
            })
            .catch(err => {
                console.error(err);
                showFriendError("请求失败，请重试");
            });
        }
    });

    // 为所有现有好友项绑定点击事件
    document.querySelectorAll(".contact").forEach(function(contactElem) {
        contactElem.addEventListener("click", function() {
            const friendName = contactElem.querySelector(".contact-name").textContent;
            switchToFriend(friendName);
        });
    });

    // 获取并更新消息列表
    function updateMessages() {
        const currentUser = localStorage.getItem('currentUser');
        if (!currentUser) return;
    
        fetch("/getMessages?" + new URLSearchParams({
            since: getLatestMessageTime() // 获取所有聊天中最新的消息时间
        }))
        .then(response => response.json())
        .then(messages => {
            // 处理新消息
            messages.forEach(msg => {
                const friend = msg.from_user === currentUser ? msg.to_user : msg.from_user;
                if (friend === currentUser) return; // Skip messages from self

                // 检查非好友消息并自动添加好友
                const existingContact = Array.from(document.querySelectorAll(".contact")).find(
                    contact => contact.querySelector(".contact-name").textContent === friend
                );

                if (!existingContact) {
                    fetch("/addFriend", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ friend: friend })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            addFriendToList(friend);
                        }
                    })
                    .catch(err => console.error("Error adding new friend:", err));
                }

                // 更新消息存储
                if (!messageStore[friend]) {
                    messageStore[friend] = [];
                }
                
                // 检查消息是否已存在
                const exists = messageStore[friend].some(m => 
                    m.timestamp === msg.timestamp && 
                    m.from_user === msg.from_user && 
                    m.message === msg.message
                );
                
                if (!exists) {
                    messageStore[friend].push(msg);
                    // 更新该好友的最后消息时间
                    lastUpdateTimes[friend] = Math.max(
                        new Date(msg.timestamp).getTime(),
                        lastUpdateTimes[friend] || 0
                    );
                    // 保存更新时间到 localStorage
                    saveLastUpdateTimes();
                }
                
                // 按时间排序
                messageStore[friend].sort((a, b) => 
                    new Date(a.timestamp) - new Date(b.timestamp)
                );
            });

            // 更新好友列表显示
            updateContactList();
        })
        .catch(err => console.error("Error updating messages:", err));
    }

    // 获取所有聊天中最新的消息时间
    function getLatestMessageTime() {
        let latestTime = 0;
        Object.values(lastUpdateTimes).forEach(time => {
            latestTime = Math.max(latestTime, time);
        });
        // 如果没有任何消息记录，返回24小时前的时间戳
        if (latestTime === 0) {
            latestTime = Date.now() - 24 * 60 * 60 * 1000;
        }
        return new Date(latestTime).toISOString();
    }

    // 将联系人列表更新逻辑抽取为独立函数
    function updateContactList() {
        const contactList = document.querySelector('.contact-list');
        const contacts = Array.from(contactList.children);
        
        contacts.forEach(contact => {
            const friendName = contact.querySelector(".contact-name").textContent;
            const messages = messageStore[friendName] || [];
            const lastMsg = messages[messages.length - 1];
            
            if (lastMsg) {
                const msgElem = contact.querySelector(".contact-msg");
                msgElem.textContent = lastMsg.message;
                
                contact.dataset.timestamp = lastMsg.timestamp;
                
                const timeElem = contact.querySelector(".contact-time");
                timeElem.textContent = formatTime(new Date(lastMsg.timestamp));
                
                // 更新未读状态
                updateUnreadBadge(contact, lastMsg);
            }
        });

        // 按最新消息时间排序
        contacts.sort((a, b) => {
            const timeA = new Date(a.dataset.timestamp || '1970-01-01');
            const timeB = new Date(b.dataset.timestamp || '1970-01-01');
            return timeB - timeA;
        });

        // 重新插入排序后的联系人
        contactList.innerHTML = '';
        contacts.forEach(contact => contactList.appendChild(contact));
    }

    // 更新未读状态的辅助函数
    function updateUnreadBadge(contact, lastMsg) {
        const currentUser = localStorage.getItem('currentUser');
        const existingBadge = contact.querySelector(".unread-badge");
        
        if (!lastMsg.is_read && lastMsg.to_user === currentUser) {
            if (!existingBadge) {
                const badge = document.createElement('div');
                badge.classList.add('unread-badge');
                contact.appendChild(badge);
            }
        } else if (existingBadge) {
            existingBadge.remove();
        }
    }

    // 格式化时间显示
    function formatTime(date) {
        const now = new Date();
        const diff = now - date;
        
        if (diff < 24 * 60 * 60 * 1000) {
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        } else {
            return date.toLocaleDateString();
        }
    }

    // 定期更新消息列表
    updateMessages();
    setInterval(updateMessages, 30000); // 每30秒更新一次

    // Update logout button text with username
    const currentUser = localStorage.getItem('currentUser');
    if (currentUser) {
        const logoutBtn = document.querySelector('#logout-btn');
        if (logoutBtn) {
            logoutBtn.textContent = `退出${currentUser}`;
        }
    }
});

// 辅助方法：将好友添加到联系人列表
function addFriendToList(name) {
    const contactList = document.querySelector('.contact-list');
    const contact = document.createElement('div');
    contact.classList.add('contact');
    contact.innerHTML = `
        <div class="contact-name">${name}</div>
        <div class="contact-msg"></div>
        <div class="contact-time"></div>
    `;
    
    // 绑定点击事件
    contact.addEventListener("click", () => switchToFriend(name));
    contactList.appendChild(contact);
    
    // 立即切换到新添加的好友
    switchToFriend(name);
}

// 辅助方法：显示错误提示
function showFriendError(message) {
    alert(message);
}

function markMessagesAsRead(friendName) {
    // 移除未读标记
    const contact = Array.from(document.querySelectorAll(".contact")).find(
        c => c.querySelector(".contact-name").textContent === friendName
    );
    if (contact) {
        const badge = contact.querySelector(".unread-badge");
        if (badge) {
            badge.remove();
        }
    }
    fetch("/markAsRead", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ friend: friendName })
    })
    .then(response => {
        if (response.ok) {
            // 更新本地消息存储中的已读状态
            if (messageStore[friendName]) {
                messageStore[friendName].forEach(msg => {
                    if (msg.to_user === localStorage.getItem('currentUser')) {
                        msg.is_read = true;
                    }
                });
            }
        } else {
            console.error("Failed to mark messages as read");
        }
    })
    .catch(err => {
        console.error("Error marking messages as read:", err);
    });
}

document.querySelector('#logout-btn').addEventListener('click', function() {
    localStorage.removeItem('currentUser');
});

// 新增显示聊天记录的函数
function showChatMessages(friendName) {
    const messagesContainer = document.getElementById("messages");
    messagesContainer.innerHTML = '';
    
    const currentUser = localStorage.getItem('currentUser');
    const messages = messageStore[friendName] || [];
    
    messages.forEach(msg => {
        const messageDiv = document.createElement("div");
        messageDiv.classList.add("message");
        
        // 根据发送者添加不同的样式
        if (msg.from_user === currentUser) {
            messageDiv.classList.add("sent");
        } else {
            messageDiv.classList.add("received");
        }
        
        messageDiv.textContent = msg.message;
        messagesContainer.appendChild(messageDiv);
    });
    
    scrollMessagesToBottom();
}

// 添加新函数处理好友选择
function switchToFriend(friendName) {
    // 更新联系人活动状态
    document.querySelectorAll(".contact").forEach(c => c.classList.remove("active"));
    const contact = Array.from(document.querySelectorAll(".contact")).find(
        c => c.querySelector(".contact-name").textContent.trim() === friendName.trim()
    );
    if (contact) {
        contact.classList.add("active");
    }

    // 显示聊天记录并标记为已读
    showChatMessages(friendName);
    markMessagesAsRead(friendName);
    
    // 更新 URL 但不刷新页面
    const newUrl = new URL(window.location);
    newUrl.searchParams.set('friend', friendName);
    window.history.pushState({}, '', newUrl);
    
    // 更新聊天窗口标题
    document.getElementById("chat-name").textContent = friendName;
}